package com.yk.test.config.oauth2;

import com.yk.test.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.yk.test.entity.User user = new com.yk.test.entity.User();
        user.setUserName(s);
        com.yk.test.entity.User userss = userMapper.findByUser(user);
        if(StringUtils.isEmpty(userss)){
            throw  new UsernameNotFoundException("用户不存在");
        }


        List<GrantedAuthority> authorities = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("test");
        authorities.add(grantedAuthority);
        return new User(userss.getUserName(),new BCryptPasswordEncoder().encode(userss.getPassword()),authorities);
    }
}
